import NoPermissionTem from '@/components/antd-comp/NoPermission'
import { showSuccess } from '@/components/antd-comp/message/useNotification'
import { useAssistantStore } from '@/store/assistantStore'
import { useBuriedEvent } from '@/util/buried'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useParams } from 'react-router-dom'
import { topLineLastPublish, topLinePublish } from './API'
import ApplicationTopLineCont from './components/ApplicationTopLineCont'
import ApplicationTopLineHead from './components/ApplicationTopLineHead'

export default function ApplicationTopLine() {
  const navigate = useNavigate()
  const { id } = useParams()
  const { assistantState } = useAssistantStore()
  const { applicationBuriedEvent } = useBuriedEvent()
  const { t } = useTranslation()

  /* cont */
  const [info, setInfo] = useState({
    logs: '',
    platform_app_on: true,
    platform_app_visable: 1,
    platform_baiying_on: false,
    platform_baiying_visable: 1,
    platform_wechat_on: false,
    platform_wechat_visable: 1
  })
  /* 上线 */
  const toplineFun = () => {
    if (TopLine) {
      navigate('/application')
      return
    }
    topLinePublish(info, id).then((res: any) => {
      let resultStatus = '失败'
      if (res) {
        showSuccess(t('prompt'), t('skills.onlineSuccessful'))
        resultStatus = '成功'
      }
      // 埋点逻辑，存在5处不同页面调用该接口，增加调用判断,非主动调起不做埋点
      const detail = {
        // @ts-expect-error ignore Type Check
        类型: assistantState.category_code,
        结果: resultStatus,
        温度数: assistantState.temperature,
        选择模型: assistantState.model_name,
        回复风格类型: assistantState.reply_style,
        知识库id: assistantState.knowledge_list.map(item => item.id),
        插件id: assistantState.tool_list.map(item => item.id)
      }
      applicationBuriedEvent({
        event_name: '【上线】按钮',
        page: '智能体配置页面',
        data_id: assistantState.id,
        detail: JSON.stringify(detail)
      })
      if (res?.preview_urls) {
        const list = endList
        endList[0].url = res?.preview_urls?.mini_program
        endList[1].url = res?.preview_urls?.web
        setEndList(list)
      }
      setTopLine(true)
      setButName('完成')
      setAssistant_id(res.release_assistant_id)
    })
  }
  /* 上线状态 */
  const [TopLine, setTopLine] = useState(false)
  const [butName, setButName] = useState('上线')
  /* 是否有权限 */
  const [permission, setPermission] = useState(true)
  /* wx内容 */
  const wxdata = [
    // {
    //   name: '微信订阅号',
    //   type: 1,
    //   checked: false
    // },
    // {
    //   name: '微信服务号',
    //   type: 2,
    //   checked: false
    // }
  ]
  /* 上线 = 端 */
  const [endList, setEndList] = useState([
    {
      name: '小程序',
      type: 'wx',
      id: '001',
      url: ''
    },
    {
      name: '网页端',
      id: '002',
      url: ''
    },
    {
      name: 'PC端',
      type: 'PC',
      id: '003',
      url: ''
    }
  ])
  /* 延迟状态 */
  const [lastLoading, setLastLoading] = useState(true)
  /* 会话id */
  const [assistant_id, setAssistant_id] = useState('')
  /* 获取最后提交记录 = 回显 */
  const lastDataFun = async () => {
    try {
      const res = await topLineLastPublish(id)
      // 检查 res 是否为空对象
      if (res && Object.keys(res).length > 0) {
        setInfo({
          logs: res.logs,
          platform_app_on: res.platform_app_on,
          platform_app_visable: res.platform_app_visable,
          platform_baiying_on: res.platform_baiying_on,
          platform_baiying_visable: res.platform_baiying_visable,
          platform_wechat_on: res.platform_wechat_on,
          platform_wechat_visable: res.platform_wechat_visable
        })
      }
    } catch (error) {
      console.error('Error fetching data:', error)
    } finally {
      setLastLoading(false) // 无论成功还是失败，都设置加载状态为 false
    }
  }

  useEffect(() => {
    lastDataFun()
  }, [])

  return (
    <div className="ApplicationTopLine_box bg-[#F4F5F8]">
      {lastLoading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <ApplicationTopLineHead toplineFun={toplineFun} butName={butName}></ApplicationTopLineHead>
      {!permission ? (
        <NoPermissionTem></NoPermissionTem>
      ) : (
        !lastLoading && (
          <ApplicationTopLineCont
            info={info}
            wxdata={wxdata}
            endList={endList}
            TopLine={TopLine}
            setInfo={setInfo}
            assistant_id={assistant_id}
          ></ApplicationTopLineCont>
        )
      )}
    </div>
  )
}
